package com.quktzhuanka.app.base;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Spanned;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.github.anzewei.parallaxbacklayout.ParallaxBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.quktzhuanka.app.MainActivity;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.activity.DialogActivity;
import com.quktzhuanka.app.activity.DialogActivity2;
import com.quktzhuanka.app.activity.SearchResultActivity;
import com.quktzhuanka.app.activity.UpdateService;
import com.quktzhuanka.app.bean.PDDBean;
import com.quktzhuanka.app.bean.PromotionDetailsBean;
import com.quktzhuanka.app.bean.Response;
import com.quktzhuanka.app.bean.VersionInformationBean;
import com.quktzhuanka.app.common.ACache;
import com.quktzhuanka.app.common.CommonUtils;
import com.quktzhuanka.app.common.LogUtils;
import com.quktzhuanka.app.common.SPUtils;
import com.quktzhuanka.app.common.T;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.https.onOKJsonHttpResponseHandler;
import com.quktzhuanka.app.login.BindPhoneActivity;
import com.quktzhuanka.app.login.LoginActivity;
import com.quktzhuanka.app.login.RegisterActivity;
import com.quktzhuanka.app.login.RetrievePasswordActvity;
import com.quktzhuanka.app.login.WelActivity;
import com.quktzhuanka.app.utils.APKVersionCodeUtils;
import com.quktzhuanka.app.utils.BroadcastContants;
import com.quktzhuanka.app.utils.BroadcastManager;
import com.quktzhuanka.app.widget.LoadingDialog;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Stack;

import cn.jiguang.analytics.android.api.CountEvent;
import cn.jiguang.analytics.android.api.JAnalyticsInterface;
import cz.msebera.android.httpclient.Header;
import jd.union.open.goods.query.request.GoodsReq;
import jd.union.open.goods.query.request.UnionOpenGoodsQueryRequest;
import jd.union.open.goods.query.response.UnionOpenGoodsQueryResponse;
import me.drakeet.materialdialog.MaterialDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Activity基类
 */
@ParallaxBack
public abstract class BaseActivity extends AppCompatActivity {

    public static final String TAG = "BaseActivity";

    public static boolean isUpdata = true;

    /**
     * 用来保存所有已打开的Activity
     */
    private static Stack<Activity> listActivity = new Stack<Activity>();

    /**
     * 记录上次点击按钮的时间
     **/
    private long lastClickTime;
    /**
     * 按钮连续点击最低间隔时间 单位：毫秒
     **/
    public final static int CLICK_TIME = 500;


    public MaterialDialog mMaterialDialog;
    private LoadingDialog loadingDialog;

    private ACache mAcache;
    String userId;
    //指纹管理
    private FingerprintManagerCompat fingerprintManager;

    public static Uri uri;
    public File file;
    private MaterialDialog downDilog;
    private View downLayout;
    private ProgressBar downProgressBar;
    private UpdateService.Builder builder;
    private boolean isDownLoadFinish = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 设置activity为无标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        int flag = getIntent().getFlags();
        //首次启动 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT 为 0
        //再次点击图标启动时就不为零了
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setStatusBar(Color.WHITE);
        mMaterialDialog = new MaterialDialog(this);//初始化MaterialDialog
        downDilog = new MaterialDialog(this);
        downLayout = LayoutInflater.from(this).inflate(R.layout.down_layout, null);
        downProgressBar = downLayout.findViewById(R.id.pb_progressbar);
        downDilog.setView(downLayout);
        downDilog.setCanceledOnTouchOutside(false);
        //初始化
        fingerprintManager = FingerprintManagerCompat.from(BaseActivity.this);

//        //拍照路径
        File mPhotoFile = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "hkx");// TODO

        // 将activity推入栈中
        listActivity.push(this);

        // 初始化ui
        initUI();
        // 初始化数据
        initData();
        // 事件监听
        initListener();
        JAnalyticsInterface.onPageStart(this, this.getClass().getCanonicalName());
        //检查版本更新
//        if (isUpdata) {
//            ArticleRequest();
//        }

    }

    protected void setStatusBar(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(color);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (color == Color.WHITE) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            if (isFlyme()) {
                CommonUtils.setMeizuStatusBarDarkIcon(this, true);
            } else if (isMIUI()) {
                CommonUtils.setMiuiStatusBarDarkMode(this, true);
            } else if (Build.MANUFACTURER.equalsIgnoreCase("OPPO")) {
                CommonUtils.setOPPOStatusTextColor(true, this);
            } else {
            }
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    /**
     * 判断手机是否是魅族
     *
     * @return
     */
    private static boolean isFlyme() {
        try {
            final Method method = Build.class.getMethod("hasSmartBar");
            return method != null;
        } catch (final Exception e) {
            return false;
        }
    }

    /**
     * 判断手机是否是小米
     *
     * @return
     */
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";

    private static boolean isMIUI() {
        Properties prop = new Properties();
        boolean isMIUI;
        try {
            prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        isMIUI = prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
//        SPUtils.getInstance().putCacheData("isMIUI",isMIUI);//保存是否MIUI
        return isMIUI;
    }

    /**
     * 初始化ui
     **/
    protected abstract void initUI();

    /**
     * 初始化数据
     **/
    protected abstract void initData();

    /**
     * 初始化监听
     **/
    protected abstract void initListener();

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    /**
     * 保存activity状态
     **/
    protected void saveInstanceState(Bundle outState) {
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public void onBack(View v) {
        finish();
    }
    public void showTipDialog3(String title, String content, final onClickListener listener,final onClickListener cancle,String okStr,String cancleStr) {
        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(this);//实例化对话框
        }
        if(cancle!=null){
            mMaterialDialog .setNegativeButton(cancleStr, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (cancle != null) {
                        cancle.onClickSure();
                    }
                    mMaterialDialog.dismiss();
                }
            });
        }
        mMaterialDialog.setTitle(title)
                .setMessage(content)
                .setPositiveButton(okStr, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            listener.onClickSure();
                        }
                        mMaterialDialog.dismiss();
                    }
                })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.MAIN");
            intent.addCategory("android.intent.category.HOME");
            startActivity(intent);
            return false;
        }else  if (keyCode == KeyEvent.KEYCODE_BACK&&this instanceof MainActivity) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        onReceiverBroadCastMessage();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (listActivity.peek() instanceof WelActivity || listActivity.peek() instanceof LoginActivity || listActivity.peek() instanceof RegisterActivity || listActivity.peek() instanceof BindPhoneActivity || listActivity.peek() instanceof RetrievePasswordActvity) {
            return;
        }
        this.getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= 23) {
                    //读取sd卡的权限
                    String[] mPermissionList = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                    if (EasyPermissions.hasPermissions(BaseActivity.this, mPermissionList)) {
                        String temp = getClipboard();
                        if (!"".equals(temp)) {
                            if (temp.contains("mobile.yangkeduo.com")) {
                                Uri uri = Uri.parse(temp);
                                if (uri.getQueryParameter("goods_id") != null && !"".equals(uri.getQueryParameter("goods_id"))) {
                                    getPddDetail(uri.getQueryParameter("goods_id"));
                                }
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 创建普通字符型ClipData
                                ClipData mClipData = ClipData.newPlainText("Label", "");
                                // 将ClipData内容放到系统剪贴板里。
                                cm.setPrimaryClip(mClipData);
                            } else if (temp.contains("item.m.jd.com/product")) {
                                getJdGoodsRequest(StringUtils.substringBetween(temp, "product/", ".html"));
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 创建普通字符型ClipData
                                ClipData mClipData = ClipData.newPlainText("Label", "");
                                // 将ClipData内容放到系统剪贴板里。
                                cm.setPrimaryClip(mClipData);
                            } else {
                                if (temp.contains("-----------------------")) {
                                    return;
                                }
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 创建普通字符型ClipData
                                ClipData mClipData = ClipData.newPlainText("Label", "");
                                // 将ClipData内容放到系统剪贴板里。
                                cm.setPrimaryClip(mClipData);
                                getGoodsMsgRequest(temp);
                            }
                        }
                    } else {
                        //未同意过,或者说是拒绝了，再次申请权限
                        EasyPermissions.requestPermissions(BaseActivity.this, "读取淘宝、京东等复制链接需要读取权限", 1, mPermissionList);
                    }
                } else {
                    String temp = getClipboard();
                    if (!"".equals(temp)) {
                        if (temp.contains("mobile.yangkeduo.com")) {
                            Uri uri = Uri.parse(temp);
                            if (uri.getQueryParameter("goods_id") != null && !"".equals(uri.getQueryParameter("goods_id"))) {
                                getPddDetail(uri.getQueryParameter("goods_id"));
                            }
                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                            // 创建普通字符型ClipData
                            ClipData mClipData = ClipData.newPlainText("Label", "");
                            // 将ClipData内容放到系统剪贴板里。
                            cm.setPrimaryClip(mClipData);
                        } else if (temp.contains("item.m.jd.com/product")) {
                            getJdGoodsRequest(StringUtils.substringBetween(temp, "product/", ".html"));
                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                            // 创建普通字符型ClipData
                            ClipData mClipData = ClipData.newPlainText("Label", "");
                            // 将ClipData内容放到系统剪贴板里。
                            cm.setPrimaryClip(mClipData);
                        } else{
                            if (temp.contains("-----------------------")) {
                                return;
                            }
                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                            // 创建普通字符型ClipData
                            ClipData mClipData = ClipData.newPlainText("Label", "");
                            // 将ClipData内容放到系统剪贴板里。
                            cm.setPrimaryClip(mClipData);
                            getGoodsMsgRequest(temp);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < grantResults.length; i++) {
//判断权限的结果，如果有被拒绝，就return
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                        T.showShort(BaseActivity.this, "您已可以在设置里重新打开该权限");
                    }
                }
            }
        }
    }

    private Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            T.showShort(getComeActivity(), "该商品没有优惠券或奖");
            super.handleMessage(msg);
        }
    };

    /**
     * @属性:获取京东推送商品详情
     * @开发者:wmm
     * @时间:2018/12/11 9:50
     */
    private void getJdGoodsRequest(String id) {
//        JAnalyticsInterface.onEvent(this,new CountEvent("jd_copy_search_lq"));
        String SERVER_URL = "https://router.jd.com/api";
        String appKey = Constants.jdappKey;
        String appSecret = Constants.jdclient_secret;
        String accessToken = "";
        final JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
        final UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
        final GoodsReq goodsReq = new GoodsReq();
        goodsReq.setSkuIds(new Long[]{Long.valueOf(id)});
        goodsReq.setPageSize(6);
        goodsReq.setPageIndex(1);
        request.setGoodsReqDTO(goodsReq);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    UnionOpenGoodsQueryResponse response = client.execute(request);
                    if (response.getData() == null) {
                        handlers.sendEmptyMessage(0);
                        return;
                    }
                    if (response.getData().length <= 0) {
                        handlers.sendEmptyMessage(0);
                        return;
                    }
                    try {
                        Intent intent = new Intent(getComeActivity(), DialogActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("goods", response.getData()[0]);
                        intent.putExtra("goods", bundle);
                        intent.putExtra("pic", response.getData()[0].getImageInfo()[0].getImageList()[0].getUrl());
                        intent.putExtra("title", response.getData()[0].getSkuName());
                        intent.putExtra("commission", "");
                        intent.putExtra("type", "jd");
                        startActivity(intent);
                    } catch (Exception e) {
                        Log.d("jddddj", "3" + e.toString());

                    }
                } catch (JdException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * @属性:获取拼多多商品详情
     * @开发者:wmm
     * @时间:2018/11/22 9:00
     */
    private void getPddDetail(final String goods_id) {
        JAnalyticsInterface.onEvent(this, new CountEvent("pdd_copy_search_lq"));
        RequestParams requestParams = new RequestParams();
        requestParams.put("goods_id", goods_id);
        HttpUtils.post(Constants.GET_PDD_DETAIL, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (getComeActivity().isDestroyed())
                    return;
                try {
                    if (new JSONObject(responseString).getInt("code") != 0) {
                        T.showShort(getComeActivity(), "该商品没有优惠券或奖");
                        return;
                    }
                    DecimalFormat df = new DecimalFormat("0.00");
                    JSONObject object = new JSONObject(responseString).getJSONObject("data").getJSONObject("goods_details");
                    Intent intent = new Intent(BaseActivity.this, DialogActivity.class);
                    Gson gson = new Gson();
                    double tem = (Double.valueOf(object.getString("min_group_price")) - Double.valueOf(object.getString("coupon_discount"))) * Double.valueOf(df.format(Double.valueOf(object.getString("promotion_rate")) / 1000));
                    object.put("commission", df.format(tem * SPUtils.getIntData(getComeActivity(), "rate", 0) / 100));
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("goods", gson.fromJson(object.toString().replace("goods_gallery_urls", "imagss"), PDDBean.class));
                    intent.putExtra("goods", bundle);
                    intent.putExtra("pic", object.getString("goods_thumbnail_url"));
                    intent.putExtra("title", object.getString("goods_name"));
                    intent.putExtra("commission", "");
                    intent.putExtra("type", "pdd");
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void checkVersion() {
        RequestParams requestParams = new RequestParams();
        HttpUtils.post(Constants.MESSAGE_ARTICLE_VERSION_URL, requestParams, new onOKJsonHttpResponseHandler<VersionInformationBean>(new TypeToken<Response<VersionInformationBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Response<VersionInformationBean> datas) {
                if (datas.isSuccess()) {
                    final VersionInformationBean data = datas.getData();
                    if (data != null) {
                        Constants.SHARE_URL = data.getShare_url();
                        Constants.VSUP_URL=data.getVy_url_s();
                        Constants.V_URL=data.getVy_url_c();
                        Constants.SHARE_URL_REGISTER = data.getShare_url_register();
                        Constants.LOOK_VIDEO_BL = data.getLool_video_bl();
                        SPUtils.saveStringData(getComeActivity(),"share_url_vip",data.share_url_vip);
                        //对比当前版本
//                        &&!"1".equals(SPUtils.getStringData(getComeActivity(),data.getVersion(),"0"))
                        if (CommonUtils.compareVersion(APKVersionCodeUtils.getVerName(getComeActivity()), data.getVersion()) == -1) {
                            showTipDialog("发现新版本", data.getContent(), new BaseActivity.onClickListener() {
                                @Override
                                public void onClickSure() {
                                    builder = UpdateService.Builder.create(data.getDown_android()).build(BaseActivity.this);
                                    downDilog.show();
                                    isDownLoadFinish = false;
                                    new Thread(new MyThread()).start();
                                }
                            }, null);
                        }
                    }
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // 要做的事情
            downProgressBar.setProgress(builder.getUpdateProgress());
            if (builder.getUpdateProgress() >= 99) {
                isDownLoadFinish = true;
                UpdateService.Builder.updateProgress = 1;
                downDilog.dismiss();
            }
            if (builder.getUpdateProgress() == -1) {
                UpdateService.Builder.updateProgress = 1;
                downDilog.dismiss();
                isDownLoadFinish = true;
                T.showShort(getComeActivity(), "下载更新失败");
            }
            super.handleMessage(msg);
        }
    };

    public class MyThread implements Runnable {
        @Override
        public void run() {
            while (!isDownLoadFinish) {
                try {
                    Thread.sleep(500);
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void getGoodsMsgRequest(final String tkl) {
        JAnalyticsInterface.onEvent(this, new CountEvent("tb_copy_search_lq"));
        String url = "";
        RequestParams requestParams = new RequestParams();
        requestParams.put("tkl", tkl);
        HttpUtils.post(Constants.SEARCHTKL, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }
            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object = new JSONObject(responseString);
                    if(object.getInt("code")==0){
                        object=object.getJSONObject("data");
                        Intent intent = new Intent(BaseActivity.this, DialogActivity.class);
                        intent.putExtra("url", tkl);
                        intent.putExtra("num_iid", object.getString("num_iid"));
                        intent.putExtra("commission", "");
                        intent.putExtra("type", "tb");
//                        startActivity(intent);
                        getDetail(object.getString("num_iid"), intent);
                    }else{
                        if (tkl.startsWith("【") && tkl.contains("http") && tkl.contains("￥")) {
                            //获取剪贴板管理器：
                            Bundle bundle = new Bundle();
                            bundle.putString("content", tkl.substring(tkl.indexOf("【") + 1, tkl.lastIndexOf("】")));
                            bundle.putInt("type", 0);//1高级搜索 0 普通搜索
                            openActivity(SearchResultActivity.class, bundle);
                            showToast(object.getString("msg"));
                        }else{
                            Intent intent=new Intent(getComeActivity(),DialogActivity2.class);
                            intent.putExtra("search",tkl);
                            startActivity(intent);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getDetail(String num_iid, final Intent intent) {
        RequestParams requestParams = new RequestParams();
        requestParams.put("num_iid", num_iid);
        HttpUtils.post(Constants.HOME_TBK_GETGOODSMSG_URL, requestParams, new onOKJsonHttpResponseHandler<PromotionDetailsBean>(new TypeToken<Response<PromotionDetailsBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Response<PromotionDetailsBean> datas) {
                if (getComeActivity().isDestroyed())
                    return;
                if (datas.isSuccess()) {
                    PromotionDetailsBean data = datas.getData();
                    if (data != null) {
                        intent.putExtra("pic", data.getPict_url());
                        intent.putExtra("title", data.getTitle());
                        intent.putExtra("one", data.getCommission());
                        intent.putExtra("two", data.getZk_final_price());
                        intent.putExtra("three", data.getCoupon_amount());
                        startActivity(intent);
                    }
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 从栈中移除当前activity
        if (listActivity.contains(this)) {
            listActivity.remove(this);
        }
        JAnalyticsInterface.onPageEnd(this, this.getClass().getCanonicalName());
    }

    /**
     * (返回TextView或者EditText的值)
     *
     * @param textView TextView对象
     */
    public String getTextEditValue(TextView textView) {

        return textView.getText().toString().trim();
    }

    /**
     * 判断EditText是否没有输入值
     *
     * @param editText EditText对象
     */
    public boolean isEditTextNoValue(EditText editText) {
        return (null == editText) || (editText.getText().toString().length() == 0);
    }

    /**
     * short吐司
     *
     * @param msg
     * @author NML
     */
    public void showToast(String msg) {
        if ("用户不存在".equals(msg)) {
            T.showShort(getApplicationContext(), "登录信息已过期");
            openActivity(WelActivity.class);
        } else {
            T.showShort(getApplicationContext(), msg);
        }
    }

    /**
     * long吐司
     *
     * @param text
     */
    public void showToastLong(String text) {
        T.showLong(getApplicationContext(), text);
    }

    /**
     * 显示圆形加载进度对话框
     */
    protected void showLoadingDialog() {
        if (!getComeActivity().isDestroyed() || !getComeActivity().isFinishing()) {
            if (loadingDialog == null) {
                loadingDialog = LoadingDialog.createDialog(this);
                loadingDialog.setMessage("正在加载..");
                loadingDialog.setCanceledOnTouchOutside(false);
            }
            loadingDialog.show();
        }
    }

    /**
     * @param msg 加载框提示语
     *            显示圆形加载进度对话框
     */
    protected void showLoadingDialog(String msg) {
        if (!getComeActivity().isDestroyed() || !getComeActivity().isFinishing()) {
            if (loadingDialog == null) {
                loadingDialog = LoadingDialog.createDialog(this);
                loadingDialog.setMessage(msg);
                loadingDialog.setCanceledOnTouchOutside(false);
            }
            loadingDialog.show();
        }
    }

    /**
     * 关闭进度对话框
     */
    protected void closeLoadingDialog() {
        if (!getComeActivity().isDestroyed() || !getComeActivity().isFinishing()) {
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
                loadingDialog = null;
            }
        }
    }

    /**********************
     * activity跳转
     **********************************/
    public void openActivity(Class<?> targetActivityClass) {
        openActivity(targetActivityClass, null);
    }

    public void openActivity(Class<?> targetActivityClass, Bundle bundle) {
        Intent intent = new Intent(this, targetActivityClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void openActivityAndCloseThis(Class<?> targetActivityClass) {
        openActivity(targetActivityClass);
        this.finish();
    }

    public void openActivityAndCloseThis(Class<?> targetActivityClass, Bundle bundle) {
        openActivity(targetActivityClass, bundle);
        this.finish();
    }

    public void openActivityForResult(Class<?> targetActivityClass, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, targetActivityClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
    }

    /***************************************************************/

    /**
     * 验证上次点击按钮时间间隔，防止重复点击
     */
    public boolean verifyClickTime() {
        if (System.currentTimeMillis() - lastClickTime <= CLICK_TIME) {
            return false;
        }
        lastClickTime = System.currentTimeMillis();
        return true;
    }

    /**
     * 收起键盘
     */
    public void closeInputMethod() {
        // 收起键盘
        View view = getWindow().peekDecorView();// 用于判断虚拟软键盘是否是显示的
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 点击空白位置 隐藏软键盘
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    /**
     * 获取string
     *
     * @param mRid
     * @return
     */
    public String getStringMethod(int mRid) {
        return this.getResources().getString(mRid);
    }

    /**
     * 获取demin
     *
     * @param mRid
     * @return
     */
    protected int getDemonIntegerMethod(int mRid) {
        return (int) this.getResources().getDimension(mRid);
    }

    /**
     * 关闭所有(前台、后台)Activity,注意：请已BaseActivity为父类
     */
    protected static void finishAll() {
        int len = listActivity.size();
        for (int i = 0; i < len; i++) {
            Activity activity = listActivity.pop();
            activity.finish();
        }
    }

    public Activity getActivitys(int index) {
        Activity activity = listActivity.get(index);
        return activity;
    }

    /**
     * 获得栈中最顶层的Activity
     *
     * @param context
     * @return
     */
    public static String getTopActivity(Context context) {
        android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

        if (runningTaskInfos != null) {
            return (runningTaskInfos.get(0).topActivity).toString();
        } else
            return null;
    }


    /*
     * ************Fragement相关方法************************************************
     *
     */
    private Fragment currentFragment;

    /**
     * Fragment替换(当前destrory,新的create)
     */
    public void fragmentReplace(int target, Fragment toFragment, boolean backStack) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        String toClassName = toFragment.getClass().getSimpleName();
        if (manager.findFragmentByTag(toClassName) == null) {
            transaction.replace(target, toFragment, toClassName);
            if (backStack) {
                transaction.addToBackStack(toClassName);
            }
            transaction.commit();
        }
    }

    /**
     * Fragment替换(核心为隐藏当前的,显示现在的,用过的将不会destrory与create)
     */
    public void smartFragmentReplace(int target, Fragment toFragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        // 如有当前在使用的->隐藏当前的
        if (currentFragment != null) {
            transaction.hide(currentFragment);
        }
        String toClassName = toFragment.getClass().getSimpleName();
        // toFragment之前添加使用过->显示出来
        if (manager.findFragmentByTag(toClassName) != null) {
            transaction.show(toFragment);
        } else {// toFragment还没添加使用过->添加上去
            transaction.add(target, toFragment, toClassName);
        }
        transaction.commit();
        // toFragment更新为当前的
        currentFragment = toFragment;
    }

    /***********************************************************************/
    /**
     * 获取点击事件
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isShouldHideKeyboard(view, ev)) {
                HideSoftInput(view.getWindowToken());
                view.clearFocus();
            }
        }
        try {
            return super.dispatchTouchEvent(ev);
        } catch (Exception e) {

        }
        return true;
    }

    /**
     * 隐藏软键盘
     */
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 点击空白区域，隐藏输入法软键盘
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                v.clearFocus();
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }


    /**
     * 对话框提示
     **/
    public void showTipDialog(String content) {

        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(this);//实例化对话框
        }
        mMaterialDialog.setTitle("友情提示")
                .setMessage(content)
                .setPositiveButton("知道啦", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMaterialDialog.dismiss();
                    }
                })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }

    public void showTipDialog(String title, Spanned content) {
        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(this);//实例化对话框
        }
        mMaterialDialog.setTitle(title)
                .setMessage(content)
                .setPositiveButton("知道啦", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMaterialDialog.dismiss();
                    }
                })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }

    public void showTipDialog2(String title, Spanned content, final onClickListener listener, String text) {
        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(this);//实例化对话框
        }
        mMaterialDialog.setTitle(title)
                .setMessage(content)
                .setPositiveButton(text, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            listener.onClickSure();
                        }
                        mMaterialDialog.dismiss();
                    }
                })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }

    public void showTipDialog(String title, String content, final onClickListener listener, final onClickListener cancle) {
        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(this);//实例化对话框
        }
        if (cancle != null) {
            mMaterialDialog.setNegativeButton("忽略此版本", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (cancle != null) {
                        cancle.onClickSure();
                    }
                    mMaterialDialog.dismiss();
                }
            });
        }
        mMaterialDialog.setTitle(title)
                .setMessage(content)
                .setPositiveButton("立即更新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            listener.onClickSure();
                        }
                        mMaterialDialog.dismiss();
                    }
                })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }

    public interface onClickListener {
        void onClickSure();
    }

    /**
     * 拨号对话框提示
     **/
    public void showCallDialog(final String msg, final String phone) {

        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(this);//实例化对话框
        }
//        final String phone = "400-888-4909";
        mMaterialDialog.setTitle("友情提示")
                .setMessage(msg)
                .setPositiveButton("呼叫", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (null != mMaterialDialog) {
                            mMaterialDialog.dismiss();
                        }
                        isCallPhone(phone);
                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (null != mMaterialDialog) {
                            mMaterialDialog.dismiss();
                        }
                    }
                })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }

    //拨打电话
    public void isCallPhone(final String phone) {
        //系统版本小于7.0
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.CALL_PHONE).build(),
                    new AcpListener() {
                        @Override
                        public void onGranted() {
                            //注意：不用用带参的构造方法 否则 android studio 环境出错，提示要你检查授权
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_CALL);
                            intent.setData(Uri.parse("tel:" + phone));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                        @Override
                        public void onDenied(List<String> permissions) {
                        }
                    });
        }

    }

    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context          上下文对象
     * @param packageName：应用包名
     * @return
     */
    public boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    @TargetApi(19)
    public void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }


    /**
     * 判断某一个类是否存在任务栈里面
     *
     * @return
     */
    public boolean isExsitMianActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        ComponentName cmpName = intent.resolveActivity(getPackageManager());
        boolean flag = false;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    flag = true;
                    break;  //跳出循环，优化效率
                }
            }
        }
        return flag;
    }


    /**
     * 提交登录信息，登录成功后 保存用户登录的token
     **/
    public void submitData(final Context context, final String account, final String pwd) {
//        if (!CommonUtils.isNetworkAvailable()) {
//            showToast(getResources().getString(R.string.error_network));
//            return;
//        }
        RequestParams params = new RequestParams();
        params.put("userName", account);//员工号
//        final DesUtil desUtil = new DesUtil(DesUtil.SECURITY_PRIVATE_KEY);
//        params.put("password", desUtil.encrypt(pwd));//登录密码
        params.put("password", pwd);//登录密码

        HttpUtils.post(true, "", params, new AsyncHttpResponseHandler() {

            //开始
            @Override
            public void onStart() {
                super.onStart();
//                showLoadingDialog("正在登录...");
            }

            //完成
            @Override
            public void onFinish() {
                super.onFinish();
//                closeLoadingDialog();
            }

            //成功
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String responseResult = new String(responseBody);


            }

            //失败
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                LogUtils.d(TAG, error.getMessage());
                showToast(error.getMessage());

                finish();
            }
        });

    }

    /**
     * 设置文本图片
     */
    public void setViewDrawable(Context mContext, TextView v, int drawable) {
        v.setVisibility(View.VISIBLE);
        v.setPadding(40, 0, 40, 0);
        Drawable dra = mContext.getResources().getDrawable(drawable);
        dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
        v.setCompoundDrawables(null, null, dra, null);
    }

    /**
     * 截取可见屏幕，包括状态栏
     */
    public static Bitmap shotScreen(Activity activity) {
        View view = activity.getWindow().getDecorView();
        Display display = activity.getWindowManager().getDefaultDisplay();
        view.layout(0, 0, display.getWidth(), display.getHeight());
        // 允许当前窗口保存缓存信息，这样getDrawingCache()方法才会返回一个Bitmap
        view.setDrawingCacheEnabled(true);
        return Bitmap.createBitmap(view.getDrawingCache());
    }

    /**
     * 截取可见屏幕，不包括状态栏
     */
    public static Bitmap shotActivity(Activity activity) {
        View view = activity.getWindow().getDecorView();
        Rect frame = new Rect();
        view.getWindowVisibleDisplayFrame(frame);
        view.setDrawingCacheEnabled(true);
        view.destroyDrawingCache();// 更新cache
        return Bitmap.createBitmap(view.getDrawingCache(), 0, frame.top, frame.width(), frame.height());
    }

    /*******************************拍照**********************************/
    /**
     * 拍照
     */
    public void photographRequest(Context context, final int code) {
        File mPhotoFile = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "cainiao");// TODO
        if (mPhotoFile.exists()) {
            mPhotoFile.delete();
        } else {
            mPhotoFile.mkdirs();
        }

        //獲取系統版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // 激活相机
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            File tempFile = new File(mPhotoFile,
                    filename + ".jpg");

            if (currentapiVersion < 24) {
                // 从文件中创建uri
                uri = Uri.fromFile(tempFile);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            }
        }


        //系统版本小于6.0
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 指定调用相机拍照后的照片存储的路径
//                mPhotoFile = new File(Environment.getExternalStorageDirectory().getPath()
//                        + File.separator + "image.jpg");// TODO
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, code);// 拍照
            } catch (Exception e) {
                e.printStackTrace();
                LogUtils.d("无法启动照相机");
            }
        } else {
            Acp.getInstance(context).request(new AcpOptions.Builder()
                    .setPermissions(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                            , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .build(), new AcpListener() {

                @Override
                public void onGranted() {
                    if (hasSdcard()) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        startActivityForResult(intent, code);
                    } else {
                        showToast("设备没有SD卡！");
                    }
                }

                @Override
                public void onDenied(List<String> permissions) {
                    //showToast("你拒绝拍照！");
                }
            });
        }


    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 从相册选择
     */
    public void selectPhoto(Context context, final int code) {
        //系统版本小于7.0
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {// 获取系统图册
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                // 要限制上传到服务器的图片类型时可以直接写如：image/jpeg 、 image/png等的类型
//                                   intent.setType("image/*");
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, code);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            Acp.getInstance(context).request(new AcpOptions.Builder()
                    .setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE
                            , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .build(), new AcpListener() {

                @Override
                public void onGranted() {
                    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                    photoPickerIntent.setType("image/*");
                    startActivityForResult(photoPickerIntent, code);
                }

                @Override
                public void onDenied(List<String> permissions) {
                    // showToast("你拒绝拍照！");
                }
            });
        }
    }

    /**
     * 是否放弃编辑
     *
     * @param context
     */
    public void isEdit(Context context, String msg) {
        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(context);//实例化对话框
        }
        mMaterialDialog.setTitle("温馨提示")
                .setMessage(msg)
                .setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMaterialDialog.dismiss();
                        finish();
                    }
                })
                .setNegativeButton("取消",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (null != mMaterialDialog) {
                                    mMaterialDialog.dismiss();
                                }
                            }
                        })
                .setCanceledOnTouchOutside(false)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }


    /**
     * @属性:接收广播是否登录消息
     * @开发者:田哥哥
     * @时间:2018/7/21 14:33
     */
    private void onReceiverBroadCastMessage() {
        BroadcastManager.getInstance(this).addAction(new String[]{BroadcastContants.sendLoginMessage, BroadcastContants.sendAllObjectMessage}, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (BroadcastContants.sendLoginMessage.equals(action)) {
                    ReceiverIsLoginMessage();
                } else {
                    String result = intent.getStringExtra("result");
                    Serializable resultSear = intent.getSerializableExtra("result");
                    ReceiverBroadCastMessage(action, resultSear, intent);
                    ReceiverBroadCastMessage(action, result, resultSear, intent);
                }
            }
        });
    }

    /**
     * @属性:
     * @开发者:田哥哥
     * @时间:2018/7/21 14:57
     */
    protected void ReceiverIsLoginMessage() {

    }


    /**
     * @属性:
     * @开发者:田哥哥
     * @时间:2018/7/21 14:57
     */
    protected void ReceiverBroadCastMessage(String status, Serializable serializable, Intent intent) {

    }

    /**
     * @属性:
     * @开发者:田哥哥
     * @时间:2018/7/21 14:57
     */
    protected void ReceiverBroadCastMessage(String status, String resultStatus, Serializable serializable, Intent intent) {

    }

    /**
     * @属性:采用接口回调结果
     * @开发者:田哥哥
     * @时间:2018/7/22 11:08
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (lisntener != null) {
            lisntener.onActivityResult(requestCode, resultCode, data);
        }
    }

    public interface onActivityResultLisntener {
        void onActivityResult(int requestCode, int resultCode, Intent data);

    }

    onActivityResultLisntener lisntener;

    /**
     * @属性:回调方法
     * @开发者:田哥哥
     * @时间:2018/7/22 11:11
     */
    public void setOnActivityResultLisntener(onActivityResultLisntener lisntener) {
        this.lisntener = lisntener;
    }

    public Activity getComeActivity() {
        return this;
    }


    /**
     * @属性:获取剪贴板内容
     * @开发者:田哥哥
     * @时间:2018/7/28 09:57
     */
    public String getClipboard() {
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        System.out.println(data);
        if (data == null)
            return "";
        ClipData.Item item = data.getItemAt(0);
        if (item == null)
            return "";
        if (item.getText() == null)
            return "";
        String content = item.getText().toString();
        return content;
    }

    /**
     * @属性:获取剪贴板内容
     * @开发者:田哥哥
     * @时间:2018/7/28 09:57
     */
    public void copyClipboard(String str) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", str);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }
}
